﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using pbvs.Utilities.Assets;
using pbvs.Data;
using pbvs.Models;
using System.Linq;

namespace pbvs.Utilities
{
    public static class Helpers
    {
        public static MvcHtmlString TextBoxFor<TModel, TProp>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProp>> expr, object htmlAttributes, bool createHelpIcon)
        { 
            MvcHtmlString txtBox = html.TextBoxFor(expr, htmlAttributes);
            StringBuilder sb = new StringBuilder();
            sb.Append(txtBox);
            if (createHelpIcon)
            {
                LambdaExpression lambda = expr;
                MemberExpression memberExpression;
                if (lambda.Body is UnaryExpression)
                {
                    UnaryExpression unaryExpression = (UnaryExpression)lambda.Body;
                    memberExpression = (MemberExpression)unaryExpression.Operand;
                }
                else
                {
                    memberExpression = (MemberExpression)lambda.Body;
                }
                PropertyInfo propInfo = typeof(TModel).GetProperty(memberExpression.Member.Name);
                using (PbvsContext db = new PbvsContext())
                {
                    FormElement elem = (from fe in db.FormElements where fe.Field == propInfo.Name select fe).FirstOrDefault();
                    if (elem != null && !string.IsNullOrEmpty(elem.HelpText))
                    {
                        TagBuilder span = new TagBuilder("span");
                        span.MergeAttribute("title", elem.HelpText);
                        span.AddCssClass("ui-icon-help");
                        span.AddCssClass("help");
                        sb.Append(span);
                    }
                }
            }
            return MvcHtmlString.Create(sb.ToString());           
        }

        public static AssetsHelper Assets(this HtmlHelper htmlHelper)
        {
            return AssetsHelper.GetInstance(htmlHelper);
        }
    }
}